<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="850px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="活动时间:">
        <template>
          <el-date-picker
            v-model="dataForm.startTime"
            style="width:220px;"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始时间"
            :disabled="dataForm.status==='进行中'"
          ></el-date-picker>
          <span style="margin: 0 5px;">至</span>
          <el-date-picker
            v-model="dataForm.endTime"
            style="width:220px;"
            type="datetime"
            :picker-options="endTimeDis"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束时间"
          ></el-date-picker>
        </template>
      </el-form-item>
      <el-form-item label="每人抽奖次数:">
        <el-radio v-model="dataForm.drawType" :label="1">总次数</el-radio>
        <el-radio v-model="dataForm.drawType" :label="2">每日</el-radio>
        <el-input
          v-model="dataForm.drawCount"
          placeholder="次数"
          style="width:180px;margin-left: 30px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="分享激励:">
        <el-radio v-model="dataForm.isShare" :label="0">关闭</el-radio>
        <el-radio v-model="dataForm.isShare" :label="1">开启</el-radio>
        <el-input
          v-if="dataForm.isShare === 1"
          v-model="dataForm.shareDrawCount"
          placeholder="分享后增加的次数"
          style="width:180px;margin-left: 30px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="每人最多抽中:">
        <el-radio v-model="dataForm.isPrize" :label="2">不限</el-radio>
        <el-radio v-model="dataForm.isPrize" :label="1">限制</el-radio>
        <el-input
          v-if="dataForm.isPrize === 1"
          v-model="dataForm.prizeDrawCount"
          placeholder="不大于总抽奖次数"
          style="width:180px;margin-left: 30px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="选择奖品:">
        <el-button @click="addList" type="primary" size="mini">添加</el-button>
        <div v-for="(item, index) in prizeList" :key="index" class="listLi">
          <el-select
            @change="(val)=> giftChange(val, index)"
            v-model="item.prizeName"
            placeholder="请选择"
            style="width:150px"
          >
            <el-option
              v-for="(item,index) in prizeEntityList"
              :key="index"
              :label="item.prizeName"
              :value="item.prizeName"
            ></el-option>
          </el-select>
          <span style="margin: 0 4px 0 15px;">奖品图</span>
          <img
            :src="item.prizeCoverUrl"
            style="width: 40px;height: 40px;border-radius: 4px;margin-right: 14px;"
          />
          <el-input v-model="item.winnerPercentage" placeholder="概率" style="width:100px"></el-input>
          <span>%</span>
          <el-input v-model="item.prizeLevel" placeholder="份数" style="width:100px"></el-input>
          <span>份</span>
          <el-button v-if="item.complete" @click="add(item, index)" type="primary" size="mini">完成</el-button>
          <el-button v-if="!item.complete&&!item.id" @click="del(index)" type="danger" size="mini">删除</el-button>
        </div>
        <div class="total_foot">
          <div>
            <span class="total">总概率</span>
            <span class="total">{{winnerPercentage}} %</span>
            <span class="total">总份数</span>
            <span class="total">{{prizeLevel}} 份</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="活动悬浮标:">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleimgSuccess"
          :before-upload="beforeimgUpload"
        >
          <img v-if="dataForm.coverUrl" :src="dataForm.coverUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-loading="dataList">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data() {
    return {
      visible: false,
      dataList: false,
      dataForm: {
        coverUrl: "",
        lotteryPrizeVOList:[],
        id:''
      },
      endTimeDis: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      winnerPercentage: 0,
      prizeLevel: 0,
      dataRule: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { max: 4, message: "最长4个字符", trigger: "blur" }
        ]
      },
      uploadUrl: "",
      prizeList: [],
      prizeEntityList: [],
    };
  },
  mounted() {
    this.uploadUrl = this.$http.adornUrl(
      `/lotterySurvey/lotteryactivity/upload?token=${this.$cookie.get("token")}`
    );
    this.getList();
  },
  methods: {
    init(id) {
      this.visible = true;
      this.dataForm.id = id;
      if(!this.dataForm.id ){
        this.dataForm = {
          coverUrl: "",
          lotteryPrizeVOList:[],
          id:''
        }
        this.prizeList = []
      }
      this.$nextTick(() => {
        // this.dataForm = {}
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/lotterySurvey/lotteryactivity/info/${id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm = data.lotteryActivityVO;
              this.prizeList = data.lotteryActivityVO.lotteryPrizeVOList;
              this.prizeList.map((item) => {
                item.winnerPercentage = item.winnerPercentage * 100
                this.winnerPercentage += parseInt(item.winnerPercentage)
                this.prizeLevel += parseInt(item.prizeLevel)
              })
            }
          });
        }
      });
      this.getList()
    },
    getList() {
      this.winnerPercentage = 0
      this.prizeLevel = 0
      // 获取奖品列表
      this.$http({
        url: this.$http.adornUrl("/lotterySurvey/lotteryprize/addedPrizeList"),
        method: "post",
        params: this.$http.adornParams({activityId: this.dataForm.id})
      }).then(({ data }) => {
        this.prizeEntityList = data.prizeEntityList;
      });
    },
    handleimgSuccess(res, file) {
      console.log(res)
      this.dataForm.coverUrl = res.url;
    },
    beforeimgUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 / 1024 < 3;
      if (!isJPG) {
        this.$message.error("上传封面只能是 png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面大小不能超过 250kb!");
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 240;
        let height = 240;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传的悬浮图标必须是240*240!");
          return Promise.reject();
        }
      );
      return isJPG && isLt2M && isSize;
    },
    // 表单提交
    dataFormSubmit() {
      this.dataForm.lotteryPrizeVOList = this.prizeList
      this.dataForm.lotteryPrizeVOList.map((item, index) => {
        item.winnerPercentage = item.winnerPercentage / 100
      })
      console.log(this.prizeList)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/lotterySurvey/lotteryactivity/saveOrUpdate"),
            method: "post",
            data: this.$http.adornData(this.dataForm)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.dataList = false
                  this.visible = false
                  this.$emit("refreshDataList")
                }
              });
            } else {
              this.dataList = false
              this.prizeList.map((item, index) => {
                item.winnerPercentage = item.winnerPercentage * 100
              })
              if (data.msg === '[drawCount不能为空]') {
                this.$message.error('请填写次数')
              } else {
                this.$message.error(data.msg)
              }
            }
          });
        }
      });
    },
    giftChange(val, index1) {
      console.log(val)
      const that = this;
      this.prizeEntityList.map((item, index) => {
        if (item.prizeName === val) {
          that.prizeList[index1].prizeId = item.id
          that.prizeList[index1].prizeName = item.prizeName
          that.prizeList[index1].prizeCoverUrl = item.prizeCoverUrl
        }
      })
      // this.prizeList[index1] = this.prizeEntityList.filter(item => {
      //   return item.prizeName === val;
      // })[0];
      this.prizeList[index1].complete = true
    },
    addList() {
      if (this.winnerPercentage < 100) {
        this.prizeList.push({
          prizeId: "",
          prizeName: "",
          prizeCoverUrl: "",
          winnerPercentage: "",
          prizeLevel: "",
          complete: true
        });
      } else {
        this.$message({
          message: "所有奖品的概率之和已为100%",
          type: "warning"
        });
      }
    },
    del(index) {
      this.prizeList[index].id = this.prizeList[index].prizeId
      this.prizeEntityList.push(this.prizeList[index]);
      this.prizeList.splice(index, 1);
      this.countSum()
    },
    add(item, index) {
      console.log(item)
      if (!item.prizeId) {
        console.log(item.prizeId)
        this.$message({
          message: "请先选择奖品～",
          type: "warning"
        });
        return;
      }
      if (!item.winnerPercentage) {
        this.$message({
          message: "请填写概率",
          type: "warning"
        });
        return;
      }
      if (!item.prizeLevel) {
        this.$message({
          message: "请填写份数",
          type: "warning"
        });
        return;
      }
      const that = this
      this.prizeList[index].complete = false;
      this.prizeEntityList.map((itemThis, index) => {
        if (itemThis.id === item.prizeId) {
          that.prizeEntityList.splice(index, 1);
        }
      })
      this.countSum(index)
    },
    // 计算总数
    countSum (index) {
      this.winnerPercentage = 0
      this.prizeLevel = 0
      this.prizeList.map((item) => {
        if (item.winnerPercentage && item.prizeLevel) {
          if ((this.winnerPercentage + parseInt(item.winnerPercentage)) <= 100) {
            this.winnerPercentage += parseInt(item.winnerPercentage)
            this.prizeLevel += parseInt(item.prizeLevel)
          } else {
            if (index > -1) {
              this.prizeList[index].complete = true
              this.prizeList[index].winnerPercentage = ''
            }
            this.$message({
              message: "所有奖品的概率加起来不能大于100%",
              type: "warning"
            });
          }
        }
      })
    }
  }
};
</script>
<style scoped>
.listLi {
  margin: 20px 0;
}
.listLi span {
  margin-left: 4px;
  margin-right: 13px;
}
.total_foot {
  margin-right: 30px;
  display: flex;
  justify-content: flex-end;
}
.total {
  padding-left: 20px;
  font-size: 15px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
